<template>
  <div class="app-container">
    <!-- <mainTilte title="预售活动商品管理" /> -->
    <form-selections :is-active="true" :items="formItems" :query-param.sync="searchParams" display="block" @handleSearch="handleSearch" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'productPresale@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="add">新增预售活动</el-button>
        <el-button v-action="'productPresale@disable'" size="small" type="danger" @click="stopClick">禁用</el-button>
        <el-button v-action="'productPresale@enable'" size="small" type="primary" @click="startClick">启用</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </div>
    <!-- <el-form ref="searchParams" :inline="true" :model="searchParams" label-width="110px">
      <div class="filters-wrap clearfix">
        <div class="filters-area">
          <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
            <el-form-item label="">
              <el-input v-model.trim="searchParams.name" placeholder="模板名称" @keyup.enter.native="handleSearch" />
            </el-form-item>
          </el-col>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button size="middle" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
        </div>
      </div>
    </el-form> -->
    <div v-loading="loading" class="page-grid">

      <egrid :screen-heigh="screenHeigh" class="egrid" stripe fit border highlight-current-row element-loading-text="正在努力加载中..." :column-type="['selection']" :data="tableData" :columns="columns" :columns-schema="columnsSchema" :columns-handler="columnsHandler" @selection-change="checkIds" />
      <epagination v-if="tableData" :total="total" :current="searchParams.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
    </div>
    <!-- 新增 -->
    <el-dialog v-if="dialogAddVisible" v-loading.lock="loading" v-loading="loading" title="" :visible.sync="dialogAddVisible" :close-on-click-modal="false" width="90%" class="dialogText header-none" element-loading-text="正在加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center @close="cancelProductClick">
      <el-form ref="form" :model="form" :rules="roleCodeRule" label-width="120px">
        <el-row>
          <mainTilte title="基础信息" />
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="名称" prop="name">
              <el-input v-model.trim="form.name" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属店铺" prop="shop_id">
              <el-select v-model.trim="form.shop_id" filterable clearable placeholder="所属店铺" @change="changeShopHandler">
                <el-option v-for="(item, index) of shopList" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="时间" prop="start_time">
              <el-date-picker v-model="date" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="datePickerOptions" @change="changeHandler" />
            </el-form-item>
            <!-- <el-form-item label="开始时间" prop="start_time">
              <el-date-picker v-model="form.start_time" class="filter-item" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="margin-right: 5px" placeholder="选择开始时间" />
            </el-form-item> -->
          </el-col>
          <!-- <el-col :span="8">
            <el-form-item label="结束时间" prop="end_time">
              <el-date-picker v-model="form.end_time" class="filter-item" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="margin-right: 5px" placeholder="选择开始时间" />
            </el-form-item>
          </el-col> -->
          <el-col :span="8">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="form.remarks" type="textarea" autosize />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <mainTilte title="商品明细信息" class="mb0" />
        </el-row>
        <div class="operation_button_box">
          <el-button type="primary" @click="selectProduct">选择商品</el-button>
        </div>
        <el-table :data="form.product" stripe fit border>
          <el-table-column type="selection" width="55" />
          <el-table-column fixed="left" label="操作" width="100" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" style="color: #ff4444" @click="delClick(scope.row)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column label="缩略图" width="150" align="center">
            <template slot-scope="scope">
              <thund :img="scope.row.image_url" />
            </template>
          </el-table-column>
          <el-table-column prop="product_code" label="系统sku" width="180" align="center" />
          <el-table-column label="预计发货日期" prop="estimated_delivery_time" min-width="180" align="center">
            <template slot-scope="scope">
              <el-form-item class="no-label" :prop="'product.' + scope.$index + '.estimated_delivery_time'" :rules="[
                  {
                    required: true,
                    message: '预计发货日期不能为空',
                    trigger: 'blur'
                  }
                ]">
                <el-date-picker v-model="scope.row.estimated_delivery_time" class="filter-item" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" style="margin-right: 5px" placeholder="选择预计发货日期" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="name_ch" label="中文名称" width="180" align="center" />
          <el-table-column prop="name_en" label="英文名称" width="180" align="center" />
          <el-table-column prop="type" label="包装类型" width="180" align="center">
            <template slot-scope="scope">
              <dic-values :dictionaries="splitOrder" :code="scope.row.packing_method" />
            </template>
          </el-table-column>
          <el-table-column prop="category_text" label="商品分类" width="180" align="center" />
          <el-table-column prop="price" label="原基准价" width="180" align="center" />
        </el-table>
        <el-row style="text-align: center; margin-top: 20px">
          <span class="dialog-footer">
            <el-button type="primary" :loading="btnLoading" @click="saveProductData">保存</el-button>
            <el-button @click="cancelProductClick">取消</el-button>
          </span>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 添加商品 -->
    <el-dialog v-if="dialogAddProductVisible" v-loading.lock="loading" v-loading="loading" title="" :visible.sync="dialogAddProductVisible" :close-on-click-modal="false" width="90%" class="dialogText header-none" element-loading-text="正在加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center>
      <addProduct :other-params="addProductParams" :issign-contract-codes="['shop-name']" @checkChildIds="checkChildIds" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddProductVisible = false">取消选择</el-button>
        <el-button type="primary" @click="saveData()">确认选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import dicValues from '@/components/dicTransform/index'
import dicTime from '@/components/dicTime/index'
import addProduct from '../portfolioManage/components/addPortProducts'
import codeItem from '@/components/base/code'
import { action } from '@/directive/permission/index.js' // 权限判断指令
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'PresaleActivity',
  components: { addProduct, dicValues },
  directives: {
    action
  },
  mixins: [list, cacheList],
  data() {
    const DICTIONARIES = {
      // 状态 2-禁用 1-启用
      isableList: [
        {
          code: 1,
          name: '启用'
        },
        {
          code: 2,
          name: '禁用'
        }
      ]
    }
    return {
      otherHeight: 355,
      formItems: [
        {
          label: '模板名称',
          key: 'name',
          type: 'input',
          placeholder: '请输入模板名称'
        },
        {
          label: '所属店铺',
          key: 'shop_id',
          type: 'select',
          placeholder: '请选择店铺',
          filterable: true,
          options: []
        }
      ],
      /** *
       * 定义搜索框
       */
      componentName: 'PresaleActivity',
      cachePaths: ['/product/presaleActivity/activityDetail'],
      searchParams: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        name: '',
        shop_id: ''
      },
      issignContract: [],
      loading: false,
      splitOrder: [
        {
          code: 1,
          name: '普通商品'
        },
        {
          code: 2,
          name: '多箱包装'
        }
      ],
      columns: [
        {
          label: '模板名称',
          prop: 'name',
          width: '200',
          align: 'center',
          tooltip: false,
          component: codeItem,
          propsHandler: function ({ row, col, column }) {
            return {
              code: row.name ? row.name : '',
              routePath: '/product/presaleActivity/activityDetail',
              queryData: { id: row.id }
            }
          }
        },
        {
          label: '所属店铺',
          prop: 'shop_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '开始时间',
          prop: 'start_time',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '结束时间',
          prop: 'end_time',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '状态',
          prop: 'is_disable',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '备注',
          prop: 'remarks',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建人',
          prop: 'creator_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'update_name',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '200',
          align: 'center',
          tooltip: false
        }
      ],
      columnsSchema: {
        状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['isableList'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        开始时间: {
          propsHandler({ col, row }) {
            return {
              code: row[col.prop]
            }
          },
          component: dicTime
        },
        结束时间: {
          propsHandler({ col, row }) {
            return {
              code: row[col.prop]
            }
          },
          component: dicTime
        }
      },
      form: {
        name: '',
        shop_id: '',
        start_time: '',
        end_time: '',
        remarks: '',
        product: []
      },
      date: [],
      roleCodeRule: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 50, message: '名称必须在50个字符以内', trigger: 'blur' }
        ],
        shop_id: [
          {
            required: true,
            message: '请选择所属店铺',
            trigger: ['change', 'blur']
          }
        ],
        start_time: [
          {
            required: true,
            message: '请选择开始时间',
            trigger: 'change'
          }
        ],
        end_time: [
          {
            required: true,
            message: '请选择结束时间',
            trigger: 'change'
          }
        ],
        remarks: [
          { max: 500, message: '备注必须在500个字符以内', trigger: 'blur' }
        ]
      },
      btnLoading: false,
      products: [
        {
          picture: '',
          goods_code: '',
          number: ''
        }
      ],
      dialogAddVisible: false,
      dialogExamineVisible: false, // 审核弹框
      examineForm: {
        value: ''
      },
      shopList: [],
      dialogAddProductVisible: false,
      rowData: {},
      isEdit: false,
      datePickerOptions: {
        disabledDate(time) {
          const date = new Date()
          date.setDate(date.getDate() - 1)
          return time.getTime() < date.getTime()
        }
      }
    }
  },
  computed: {
    addProductParams() {
      const vm = this
      return {
        shop_id: vm.form.shop_id,
        type: 0
      }
    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.query()
    this.queryShopAsync()
    this.getShop()
  },
  methods: {
    // 获取店铺
    getShop() {
      const vm = this
      const params = { limit: 100000, page: 1 }
      vm.$http.get(`/shop`, { params: params }).then(res => {
        const data = res.data.map((arr) => {
          return {
            value: arr.id,
            label: arr.shop_name
          }
        })
        vm.formItems = vm.formItems.map(arr => {
          if (arr.key === 'shop_id') {
            arr.options = data
          }
          return arr
        })
      })
    },
    // 修改店铺处理函数
    changeShopHandler(e) {
      this.form.product = []
    },
    handleSearch() {
      const vm = this
      vm.searchParams.page = 1
      vm.query()
    },
    handleRefresh() {
      const vm = this
      vm.searchParams.page = 1
      vm.searchParams.limit = 10
      vm.searchParams.name = ''
      vm.searchParams.shop_id = ''
      vm.query()
    },
    // 店铺查询
    queryShopAsync() {
      const params = {
        page: 1,
        limit: 100000000,
        status: 1
      }
      this.$http
        .get(`/shop`, { params })
        .then((res) => {
          if (res.code === 10000 && res.data && res.data.length > 0) {
            this.shopList = res.data.map((item) => {
              return { name: item.shop_name, id: item.id }
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 点击搜索
    query() {
      this.initTableData(
        `/productPresale?page=${this.searchParams.page}&limit=${this.searchParams.limit}&shop_id=${this.searchParams.shop_id}&name=${this.searchParams.name}`
      )
    },
    // 确认选择
    saveData() {
      const dataLength = this.checkChildList.length

      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      console.log(this.checkChildList)
      // this.form.shop_id = this.checkChildList[0].shop_id;
      this.checkChildList.forEach((ele) => {
        const index = this.form.product.findIndex(
          (e) => e.product_id === ele.product_id
        )
        if (index > -1) {
          this.form.product.splice(index, 1)
        }
        const productObj = {
          image_url: ele.image_url,
          product_code: ele.product_code,
          name_ch: ele.name_ch,
          name_en: ele.name_en,
          packing_method: ele.packing_method,
          type: ele.type === 0 ? '内部员工' : '客户商品', // 商品所属客户类型 0-内部员工 1-客户商品
          category_name: ele.category_name, // 商品分类
          category_text: ele.category_text, // 商品分类
          price: ele.type === 0 ? ele.benchmark_price : ele.purchase_price_usd, // 基准价
          product_id: ele.product_id,
          estimated_delivery_time: ''
        }
        this.form.product.push(productObj)
      })
      this.dialogAddProductVisible = false
    },
    checkChildIds(data) {
      this.checkChildList = data
    },
    // 选择商品
    selectProduct() {
      if (!this.form.shop_id) {
        return this.$message.error('请选择所属店铺')
      }
      this.dialogAddProductVisible = true
    },
    initForm() {
      this.form.name = ''
      this.form.shop_id = ''
      this.form.start_time = ''
      this.form.end_time = ''
      this.form.remarks = ''
      this.form.product = []
    },
    // 新增
    add() {
      this.initForm()
      this.date = []
      this.dialogAddVisible = true
    },
    editList() {
      this.$http
        .get(`/productPresale/${this.rowData.id}`)
        .then((res) => {
          if (res.code === 10000) {
            this.form = res.data
            this.form.product = res.data.list
            this.form.product.forEach((ele) => {
              ele['product_code'] = ele.code
              ele['category_text'] = `${ele.parent_name}-${ele.category_name}`
              ele['price'] = ele.benchmark_price
              if (ele.estimated_delivery_time) {
                ele.estimated_delivery_time = this.timestampToTime(
                  ele.estimated_delivery_time
                )
              }
            })
            this.form.start_time = this.timestampToTime(this.form.start_time)
            this.form.end_time = this.timestampToTime(this.form.end_time)
            this.date = [this.form.start_time, this.form.end_time]
            console.log(this.form.product, 'this.form.product')
            // console.log(typeof(this.form.start_time),'shijian')
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    // 时间戳转化成时间格式
    timestampToTime(timestamp) {
      // timestamp是整数，否则要parseInt转换,不会出现少个0的情况
      var time = new Date(timestamp * 1000)
      var year = time.getFullYear()
      var month = time.getMonth() + 1
      var date = time.getDate()
      var hours = time.getHours()
      var minutes = time.getMinutes()
      var seconds = time.getSeconds()
      return (
        year +
        '-' +
        this.add0(month) +
        '-' +
        this.add0(date) +
        ' ' +
        this.add0(hours) +
        ':' +
        this.add0(minutes) +
        ':' +
        this.add0(seconds)
      )
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          const isShow = row.is_disable === 2
          return {
            row,
            edit: isShow,
            del: false,
            delAction: 'productPresale@delete',
            editAction: 'productPresale@update'
          }
        },
        component: operationBtnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          editTableClick(row) {
            that.rowData = JSON.parse(JSON.stringify(row))
            that.dialogAddVisible = true
            that.isEdit = true
            that.editList()
          }
          // deleteTableClick(row) {
          //   that
          //     .$confirm('确认要删除？', '提示', {
          //       distinguishCancelAndClose: true,
          //       confirmButtonText: '确定',
          //       cancelButtonText: '取消',
          //       type: 'warning'
          //     })
          //     .then(() => {
          //       that.$http
          //         .delete(`/productPresale/${row.id}`)
          //         .then((res) => {
          //           if (res.code === 10000) {
          //             that.$message.success('删除成功')
          //             that.query()
          //           }
          //         })
          //         .catch((err) => {
          //           console.log(err)
          //         })
          //     })
          //     .catch((action) => { })
          // }
        }
      })
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        )
      }
    },
    handleSelect() { },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000
    },
    saveProductData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.product.length <= 0) {
            return this.$message.error('请至少选择添加一个商品')
          }
          this.btnLoading = true
          const data = JSON.parse(JSON.stringify(this.form))
          let param = {
            start_time: this.getTimestamp(data.start_time),
            end_time: this.getTimestamp(data.end_time)
          }
          const newObj = Object.assign(data, param)
          param = JSON.parse(JSON.stringify(newObj))
          param.product.forEach((item) => {
            if (item.estimated_delivery_time) {
              item.estimated_delivery_time = this.getTimestamp(
                item.estimated_delivery_time
              )
            }
          })
          if (this.isEdit) {
            delete param.created_at
            delete param.updated_at
            // 编辑
            this.$http
              .put(`/productPresale/${this.form.id}`, param)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('修改成功')
                  this.query()
                  this.dialogAddVisible = false
                }
                this.btnLoading = false
              })
              .catch((err) => {
                this.btnLoading = false
                console.log(err)
              })
          } else {
            this.$http
              .post(`/productPresale`, param)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('新增成功')
                  this.query()
                  this.dialogAddVisible = false
                  this.isEdit = false
                }
                this.btnLoading = false
              })
              .catch((err) => {
                this.btnLoading = false
                console.log(err)
              })
          }
        }
      })
    },
    cancelProductClick() {
      this.dialogAddVisible = false
    },
    // 点击审核按钮
    examineClick() {
      this.dialogExamineVisible = true
    },
    // 修改日期处理函数
    changeHandler(e) {
      if (e?.length === 2) {
        this.form.start_time = e[0]
        this.form.end_time = e[1]
      } else {
        this.form.start_time = ''
        this.form.end_time = ''
      }
    },
    // 确认审核
    saveExamineData() { },
    // 禁用
    stopClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }
      vm.$confirm(`确定批量禁用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/productPresale/disable`, { ids: vm.ids })
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('禁用成功')
              vm.query()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    startClick() {
      const vm = this
      const dataLength = vm.checkedList.length
      if (dataLength === 0) {
        vm.$message.error('请至少选择一条数据')
        return false
      }

      vm.$confirm(`确定批量启用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http
          .post(`/productPresale/enable`, { ids: vm.ids })
          .then((res) => {
            if (res.code === 10000) {
              vm.$message.success('启用成功')
              vm.query()
            }
          })
          .catch((err) => {
            console.log(err)
          })
      })
    },
    delClick(row) {
      this.form.product = this.form.product.filter((item) => {
        return item !== row
      })
      this.$forceUpdate()
    },
    handleSizeChange(val) {
      this.searchParams.limit = val
      this.query()
    },
    handleCurrentChange(val) {
      this.searchParams.page = val
      this.query()
    }
  }
}
</script>

<style scoped>
.addExpense {
  padding: 15px;
  background: #fff;
}
.app-container /deep/.el-select,
.el-autocomplete,
.el-date-editor {
  width: 100%;
}
.sizeStyle {
  display: flex;
}
.sizeStyle /deep/ .el-input__inner {
  border-right: 0;
}
.sizeStyle /deep/ .el-input-group__append {
  padding-left: 4px;
  padding-right: 4px;
  font-size: 14px;
  color: #333333;
  background: #fff;
}
</style>
